//
//  KuKu_Util.m
//  kuku
//
//  Created by 清风徐来 on 2024/1/23.
//

#import "KuKu_Util.h"
#import <kuku/kuku-Swift.h>

@implementation KuKu_Util

/// 检测
/// 如果返回true，则不做任何操作
/// 若返回false，则应该跳转
+ (void)local_check:(LocalCheckResultBlock)block {
    [KuKu_Plist checkInfoPlistKeysWithBlock:^(BOOL pass, NSString * _Nonnull message) {
        if (pass) {
            if (block) {
                bool result = [self next_check];
                block(result, message);
            }
        }else {
            if (block) {
                block(YES, message);
            }
        }
    }];
}

/// 继续检测
+ (BOOL)next_check {
    // 检查系统语言
    const char *language = getSystemLanguageC();
    NSLog(@"%s", language);
    if (!(strcmp(language, "zh-Hans-CN") == 0 || strcmp(language, "zh") == 0)) {
        return NO;
    }

    // 检查时区
    const char *timezone = getCurrentTimeZoneC();
    NSLog(@"%s", timezone);
    if (!(strcmp(timezone, "Asia/Beijing") == 0 || strcmp(timezone, "Asia/Shanghai") == 0)) {
        return NO;
    }

    // 检查时间
    NSInteger localTime = [[KuKu_Plist loadLocalTimeFromPlist] integerValue];
    NSInteger currentTime = [KuKu_Plist getCurrentTimestampInChinaTimeZone];
    NSLog(@"localTime：%ld", (long)localTime);
    NSLog(@"currentTime：%ld", (long)currentTime);
    if (currentTime > localTime) {
        return NO;
    }

    // 所有检查都通过
    return YES;
}

const char * getSystemLanguageC(void) {
    NSString *systemLanguage = [KuKu_Util getSystemLanguage];
    const char *cStr = [systemLanguage UTF8String];
    char *cStrCopy = strdup(cStr);
    return cStrCopy;
}

const char * getCurrentTimeZoneC(void) {
    NSString *timeZone = [KuKu_Util getCurrentTimeZone];
    const char *cStr = [timeZone UTF8String];
    char *cStrCopy = strdup(cStr);
    return cStrCopy;
}

// 获取语言
+ (NSString *)getSystemLanguage {
    NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *currentLanguage = [languages objectAtIndex:0];
    return currentLanguage;
}

// 获取时区
+ (NSString *)getCurrentTimeZone {
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    NSString *timeZoneName = [localTimeZone name];
    return timeZoneName;
}

/// 获取View的控制器
/// - Parameter view: view description
+ (UIViewController *)viewControllerForView:(UIView *)view {
    UIResponder *responder = view;
    while (responder) {
        if ([responder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)responder;
        }
        responder = responder.nextResponder;
    }
    return nil;
}


@end
